﻿using System.Collections.Generic;
using System.Web.Mvc;
using BLL.Installer;
using BLL.Interface.User;
using BLL.Model.User;
using WayCloud.ViewModel;

namespace WayCloud.Controllers.Register
{
    public class RegisterController : Controller
    {
        public RoleInfo DefaultRole
        {
            get
            {
                var roleInfoManager = ContainerHelper.Instance.Container.Resolve<IRoleInfo>();
                return roleInfoManager.FindRoleInfoByName("user");
            }
        }

        public ActionResult Index()
        {
            return View("Register");
        }

        [HttpGet]
        public ActionResult CheckAccountName(string accountName)
        {
            accountName = accountName.Trim();
            var userInfoManager = ContainerHelper.Instance.Container.Resolve<IUserInfo>();
            return Json(!userInfoManager.CheckAccountNameExists(accountName), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult RegisertUser(RegisterInfo user)
        {
            if (!ModelState.IsValid)
            {
                return View("Register", user);
            }

            var userInfo = new UserInfo
                               {
                                   AccountName = user.AccountName.Trim(),
                                   Email = user.Email.Trim(),
                                   Password = user.Password.Trim(),
                                   Phone = user.Phone.Trim(),
                                   UserName = user.UserName.Trim(),
                                   RoleList = new List<RoleInfo> { DefaultRole }
                               };
            var userInfoManager = ContainerHelper.Instance.Container.Resolve<IUserInfo>();
            var result = userInfoManager.AddUserInfo(userInfo);
            ViewBag.Message = result;
            return View("Register", user);
        }

    }
}
